package com.yeexun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeexun.domain.User;
import com.yeexun.mapper.UserMapper;
import com.yeexun.service.UserService;
import com.yeexun.util.HttpUtils;
import com.yeexun.util.Result;
import com.yeexun.util.ResultGenerator;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yeexun.util.HttpClientUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author rookie
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result login(String code, String imageUrl, String nickName) {
        System.out.println(imageUrl);

        // 第一步、根据小程序登录,接收到code之后,需要请求微信服务器发送请求,
        //        登录凭证校验接口，需要携带appid,appsecret和code。
        String appid = "wx71e72ca4e7431c8c";
        String appsecret = "f62a67d66e20855a0f91219334e007d3";
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appid +
                "&secret=" + appsecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        // 第二步、发送请求
        String responseData = HttpClientUtil.doGet(url);
        System.out.println(responseData);
        //转换为json
        JSONObject jsonObject = JSONObject.parseObject(responseData);
        //获得openid
        String openId = (String)jsonObject.get("openid");
        //根据openid查询用户
        if(openId!=null){
            User user = userMapper.selectByOpenId(openId);
            if (user==null){
                User newUser = new User();
                newUser.setUserName(nickName);
                newUser.setOpenId(openId);
                newUser.setUserImageUrl(imageUrl);
                newUser.setState(0);
                //添加新用户
                userMapper.insert(newUser);
                return ResultGenerator.genSuccessResult(newUser);
            }
            user.setUserName(nickName);
            user.setUserImageUrl(imageUrl);
            //更新最新数据
            userMapper.updateByPrimaryKey(user);
            return ResultGenerator.genSuccessResult(user);
        }
        return ResultGenerator.genFailResult("登录失败了");
    }

    /**
     * //  短信验证
     * @param phone
     * @return
     */
    @Override
    public Result verification(String phone){

        String host = "https://feginesms.market.alicloudapi.com";
        String path = "/codeNotice";
        String method = "GET";
        //阿里云appCode
        String appcode = "a55b99e70e2b4860a0fe8056265719b8";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        //生成验证码
        Long param = Math.round((Math.random()+1) * 1000);
        //这里是验证码哈
        querys.put("param", param.toString());
        //然后这里是手机号
        querys.put("phone", phone);
        //签名编号【联系旺旺客服申请，测试请用1】
        querys.put("sign", "1");
        //模板编号【联系旺旺客服申请，测试请用1~21】
        querys.put("skin", "1");
        //JDK 1.8示例代码请在这里下载：  http://code.fegine.com/Tools.zip

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 或者直接下载：
             * http://code.fegine.com/HttpUtils.zip
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             * 相关jar包（非pom）直接下载：
             * http://code.fegine.com/aliyun-jar.zip
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            String message = EntityUtils.toString(response.getEntity());
            System.out.println(message);
            //转换为json
            JSONObject jsonObject = JSONObject.parseObject(message);
            String ok =  (String) jsonObject.get("Message");
            if ("OK".equals(ok)){
                return ResultGenerator.genSuccessResult(param.toString());
            }else {
                return  ResultGenerator.genFailResult("失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return  ResultGenerator.genFailResult("失败");
        }
    }

    /**
     * //    绑定手机号
     * @param userId
     * @param phone
     * @return
     */
    @Override
    public User bindingPhone(Integer userId, String phone) {

        User user = userMapper.selectByPrimaryKey(userId);
        user.setPhone(phone);
//        更新用户信息
        userMapper.updateByPrimaryKey(user);
//        返回最新用户信息
        return user;
    }

}
